package com.mingrisoft.weixin;

import com.google.gson.Gson;
import com.mingrisoft.domain.Result;
import com.mingrisoft.utils.URLUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by  Administrator on  2018/11/8
 */
@WebServlet("/weixin/auth")
public class WeixinAuthApi extends HttpServlet {

    //保密
    private static final String APPID = "wxf7f7bd216a1d35c3";
    private static final String SECRET = "f4ee5f6a704d1b305636e8cf270bdb17";

    /**
     * 通过code换取网页授权access_token
     * 获取code后，请求以下链接获取access_token：  https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String code = request.getParameter("code");
        String uuid = request.getParameter("uuid");

        response.setHeader("Content-Type","application/json;charset=utf-8");

        if(uuid == null){
            Result.genErrResult("二维码来源不正确",response);
            return;
        }

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID +
                "&secret=" + SECRET +
                "&grant_type=authorization_code&code=" + code;
        String res = URLUtils.sendGet(url);

        Map<String,Object> resMap = new Gson().fromJson(res,Map.class);

        System.out.println(resMap);

        //返回openid,即授权成功
        if(resMap.get("openid") != null){
            //根据openid获取用户信息


            request.getServletContext().setAttribute(uuid,"1");

            response.getOutputStream().write("授权成功".getBytes("utf-8"));
        }else {
            Result.genErrResult("授权失败",response);
        }

    }
}
